package mobi.daogu.powerstripcontroller.remote

import android.os.Handler
import android.os.HandlerThread
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL

/**
 * @FileName: RemoteServer
 * @Desc:
 * @Author gene
 * @Date: 2024/11/20 10:37
 */
class RemoteServer(private val debugPrinter: (String) -> Unit = {}) {
    private val HOST = "http://120.48.180.180:3389"
    private val REQ_PWS_BASE = "$HOST/pws"
    private val REQ_GET_PW_STATUS = "$REQ_PWS_BASE/getscd?v=1"
    private val workThread = HandlerThread("RemoteServer")
    private val workHandler: Handler

    private val getStatusRunnable = Runnable {
        getPowerStatus()
    }

    init {
        workThread.start()
        workHandler = Handler(workThread.looper)
    }

    fun startSync() {
        workHandler.post(getStatusRunnable)
    }

    fun pauseSync() {
    }

    fun stop() {
        workHandler.removeCallbacksAndMessages(null)
        workThread.quitSafely()
    }

    private fun doHttpGet(requestUrl: String, callback: (Boolean, String, String) -> Unit) {
        workHandler.post {
            debugPrinter("doHttpGet: $requestUrl")
            val url = URL(requestUrl)
            val connection = url.openConnection() as HttpURLConnection
            connection.requestMethod = "GET"

            val responseCode = connection.responseCode
            if (responseCode == HttpURLConnection.HTTP_OK) {
                val bufferedReader = BufferedReader(InputStreamReader(connection.inputStream))
                val response = StringBuffer()
                var inputLine: String?
                while (bufferedReader.readLine().also { inputLine = it } != null) {
                    response.append(inputLine)
                }
                bufferedReader.close()
                callback(true, responseCode.toString(), response.toString())
            } else {
                callback(false, responseCode.toString(), "")
            }
        }
    }

    private fun getPowerStatus() {
        doHttpGet(REQ_GET_PW_STATUS) { success, responseCode, response ->
            if (success) {
                debugPrinter("getPowerStatus success: $response")
            }
        }
        workHandler.postDelayed(getStatusRunnable, 1000 * 10)
    }
}